package com.seekprice.core.impl;

import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.seekprice.constant.Constant;
import com.seekprice.core.Extractor;
import com.seekprice.core.Product;

public class Buy360Extractor implements Extractor {
	
	private static Logger logger = LoggerFactory.getLogger(Buy360Extractor.class);

	public List<Product> search(String key) {
		logger.debug("查询关键字为:'{}'",key);
		try {
			Document doc = Jsoup
					.connect(Constant.BUY360_URL + key)
					.userAgent(Constant.USERAGENT)
					.timeout(Constant.TIMEOUT).post();
			Elements resultList = doc.select("#plist");
			Elements productList = resultList.select("li");
			
			List<Product> seekResult=new ArrayList<Product>();

			for (int i = 0; i < productList.size(); i++) {
				Element product = productList.get(i);
				String title = product.getElementsByClass("p-name").first().getElementsByTag("a").first().text();
				if (title.contains(key) == false) {
					continue;
				}
				String url = product.getElementsByClass("p-name").first().getElementsByTag("a").first().attr("href");
				String img = product.getElementsByClass("p-img").first().select("img").first().attr("src");
				String price = product.getElementsByClass("p-price").first().getElementsByTag("del").first().text();
				String evaluateUrl = product.getElementsByClass("extra").first().getElementsByTag("a").first().attr("href");
				String evaluateQuantity = product.getElementsByClass("extra").first().getElementsByTag("a").first().text();
				System.out.println("title:" + title);
				System.out.println("url:" + url);
				System.out.println("img:" + img);
				System.out.println("price:" + price);
				System.out.println("evaluateUrl:" + evaluateUrl);
				System.out.println("evaluateQuantity:" + evaluateQuantity);
				
				Product entity=new Product();
				entity.setShop("京东商城");
				entity.setTitle(title);
				entity.setPrice(price);
				entity.setUrl(url);
				entity.setImg(img);
				entity.setEvaluateQuantity(evaluateQuantity);
				entity.setEvaluateUrl(evaluateUrl);
				seekResult.add(entity);
			}
			return seekResult;
		} catch (Exception e) {
			logger.error("解析出错!",e);
		}
		return java.util.Collections.emptyList();
	}
}
